import { useDispatch, useSelector } from 'react-redux';
import type { GlobalState } from '@/store';
import { routes } from '@/routes';
import useLocale from '@/utils/useLocale';
import { useEffect, useRef, useState } from 'react';
import { useAliveController } from 'react-activation';
const updateTabActionName = 'update-tabList';
const homePath = '/dashboard/workplace';
/**
 *
 * @param _routes
 * @param url
 * @returns 从路由表中搜索和url匹配的路由
 */
const searchCurrentRoute = (_routes, url) => {
  for (const e of _routes) {
    if ('/' + e.key === url) {
      return e;
    }
    if (e.children?.length > 0) {
      const res = searchCurrentRoute(e.children, url);
      if (res) {
        return res;
      }
    }
  }
  return null;
};

/**
 *  navTabbarInfo的操作hooks
 */
export const useTabActions = () => {
  const { navTabbarInfo } = useSelector((state: GlobalState) => state);
  const aliveController = useAliveController();
  const navTabbarInfoRef = useRef(navTabbarInfo); //navTabbar的缓存信息
  const locale = useLocale();
  const dispatch = useDispatch();

  useEffect(() => {
    if (navTabbarInfoRef.current !== navTabbarInfo) {
      navTabbarInfoRef.current = navTabbarInfo;
    }
  }, [navTabbarInfo]);

  //删除缓存
  const deleteKeepAliveCache = (tabKey: string) => {
    const delKey = tabKey.startsWith('/') ? tabKey.replace('/', '') : tabKey;
    //TODO: 已知异常drop无法删除缓存, 而clear可清除缓存
    return aliveController.drop(delKey);
  };

  return {
    navTabbarInfo,
    switchTab: (tabKey) => {
      const url = tabKey;
      const thisTab = navTabbarInfoRef.current.tabs.find((e) => e.key === url);
      if (thisTab) {
        navTabbarInfoRef.current.activeKey = thisTab.key;
      } else {
        const currentRoute = searchCurrentRoute(routes, url);
        if (currentRoute) {
          navTabbarInfoRef.current.tabs.push({
            key: url,
            title: locale[currentRoute.name],
          });
          navTabbarInfoRef.current.activeKey = url;
        }
      }
      dispatch({
        type: updateTabActionName,
        payload: {
          ...navTabbarInfoRef.current,
        },
      });
    },
    closeTab: (tabKey) => {
      const activeIndex = navTabbarInfoRef.current.tabs.findIndex(
        (e) => e.key === tabKey
      );
      if (activeIndex > -1) {
        navTabbarInfoRef.current.tabs.splice(activeIndex, 1);

        const currentTab = navTabbarInfoRef.current.tabs[
          Math.min(navTabbarInfoRef.current.tabs.length - 1, activeIndex)
        ] ?? { key: homePath, title: '工作台' };
        navTabbarInfoRef.current.activeKey = currentTab.key;
        if (navTabbarInfoRef.current.tabs.length <= 0) {
          navTabbarInfoRef.current.tabs = [currentTab];
        }
        dispatch({
          type: updateTabActionName,
          payload: {
            ...navTabbarInfoRef.current,
          },
        });
        deleteKeepAliveCache(currentTab.key);

        return currentTab;
      }
    },
    closeCurrentTabbar: () => {
      dispatch({
        type: updateTabActionName,
        payload: {
          tabs: [],
          activeKey: null,
        },
      });
    },
    closeAllOtherTabs: (tabKey) => {
      const url = tabKey;
      const thisTab = navTabbarInfoRef.current.tabs.find((e) => e.key === url);
      dispatch({
        type: updateTabActionName,
        payload: {
          tabs: [thisTab],
          activeKey: thisTab.key,
        },
      });
    },
    closeAllTabs: () => {
      dispatch({
        type: updateTabActionName,
        payload: {
          tabs: [],
          activeKey: null,
        },
      });
    },
  };
};

export default useTabActions;
